package handler

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"strconv"
	"time"
	"yunpan/cache/log"
	mydb "yunpan/db"
	"yunpan/util"
)

const (
	PWD_SALT = "sf8*ff&^5fsa"
	TOKEN_SALT = "fffff"
	TOKEN_EXPIR = 3600*24
)

func SignupHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	if r.Method == http.MethodGet {
		data, err := ioutil.ReadFile("./static/view/signup.html")
		if err != nil {
			log.Ob().Warn("internel server")
			return
		}
		io.WriteString(w, string(data))
	} else if r.Method == http.MethodPost {
		username := r.Form.Get("username")
		pwd := r.Form.Get("password")
		if len(username) < 3 || len(pwd) < 3 {
			w.Write([]byte("用户名或密码过短"))
			return
		}

		pwd_enc := util.MD5([]byte(PWD_SALT+pwd))

		res := mydb.UserSignup(username, pwd_enc)
		if res {
			w.Write([]byte("SUCCESS"))
		} else {
			w.Write([]byte("failed"))
		}
	}
}

func SignInHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	username := r.Form.Get("username")
	pwd := r.Form.Get("password")
	pwdEnc := util.MD5([]byte(PWD_SALT+pwd))
	
	checked := mydb.UserSignin(username, pwdEnc)
	if !checked {
		w.Write([]byte("failed"))
		return
	}

	token := GenToken(username)

	res := mydb.UpdateToken(username, token)
	if !res {
		w.Write([]byte("failed"))
		return
	}
	resp := util.RespMsg{
		Code: 0,
		Msg:  "OK",
		Data: struct {
			Location string
			Username string
			Token string
		}{
			Location: "http://"+r.Host+"/static/view/home.html",
			Username: username,
			Token: token,
		},
	}

	w.Write(resp.JSONBytes())
}

func UserInfoHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	username := r.Form.Get("username")
	//token := r.Form.Get("token")
	//
	////验证token是否有效
	//tokenValid := IsTokenValid(username, token)
	//if !tokenValid {
	//	w.WriteHeader(http.StatusForbidden)
	//	return
	//}

	//查询用户信息
	user, err := mydb.GetUserInfo(username)
	if err != nil {
		w.WriteHeader(http.StatusForbidden)
		return
	}
	resp := util.RespMsg{
		Code: 0,
		Msg:  "OK",
		Data: user,
	}

	w.Write(resp.JSONBytes())
}


func GenToken(username string) string {
	ts := fmt.Sprintf("%x", time.Now().Unix())
	tokenPrefix := util.MD5([]byte(username+ts+TOKEN_SALT))
	return tokenPrefix+ts[:8]
}

func IsTokenValid(username, token string) bool {
	if len(token) != 40 {
		return false
	}
	//token过期时间
	ts, _ := strconv.ParseInt(token[len(token)-8:], 16, 32)
	now_ts := time.Now().Unix()
	if  (now_ts - ts) > TOKEN_EXPIR {
		return false
	}
	//查询token是否一致
	res := mydb.TokenValid(username, token)
	if res {
		return true
	}
	return false
}
